/*
 *  ConcreteNoteGeneratorSelectro.cpp
 *  SoundController0002
 *
 *  Created by jiro on 11/10/10.
 *  Copyright 2011 jiro music. All rights reserved.
 *
 */

#include "ConcreteNoteGeneratorSelector.h"
#include "ConcreteNoteGenerator.h"
#include "../../sc/Utility.h"

namespace sc
{
namespace system0039
{
	void ConcreteNoteGeneratorSelector::AddGenerator( const ConcreteNoteGenerator& generator, double probablity )
	{
		generators.push_back( generator );
		probablities.push_back( probablity );
	}

	void ConcreteNoteGeneratorSelector::SetProbablity( int index, double probablity )
	{
		probablities[ index ] = probablity;
	}

	const ConcreteNoteGenerator& ConcreteNoteGeneratorSelector::Select() const
	{
		double randomValue = ::sc::RandomValueGenerator::GetValue( 0.0, 1.0 );
		double fraction = 0.0;
		int count = generators.size();
		for ( int i = 0; i < count; i++ )
		{
			fraction += probablities[ i ];
		}

		double lowerValue = 0.0;
		double higherValue = 0.0;
		for ( int i = 0; i < count; i++ )
		{
			higherValue += probablities[ i ] / fraction;
			if ( lowerValue <= randomValue and randomValue < higherValue )
			{
				return generators[ i ];
			}
			lowerValue = higherValue;
		}
		return generators.back();
	}

	int ConcreteNoteGeneratorSelector::GetGeneratorCount() const
	{
		return generators.size();
	}
	
	bool ConcreteNoteGeneratorSelector::operator == ( const ConcreteNoteGeneratorSelector& rhs ) const
	{
		if ( generators == rhs.generators and
			 probablities == rhs.probablities )
		{
			return true;
		}
		return false;
	}

}
}